package org.nf.trading.service.app.circle.mq;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.nf.trading.config.RabbitConfig;
import org.nf.trading.dto.LikeDTO;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @author wangl
 * @date 2023/12/7
 * 发送点赞信息到mq
 */
@Service
@RequiredArgsConstructor
public class LikeSyncProducer {

    private final RabbitTemplate template;

    public void send(LikeDTO dto) {
        try {
            CorrelationData data = new CorrelationData(UUID.randomUUID().toString());
            byte[] bytes = new ObjectMapper().writeValueAsBytes(dto);
            Message message = new Message(bytes);
            //封装一个callback的返回消息，在confirmCallback中可以通过CorrelationData得到ReturnedMessage对象
            ReturnedMessage returnedMessage = new ReturnedMessage(message, 0, "likeConfirmCallbackService",
                    RabbitConfig.DIRECT_EXCHANGE_NAME, RabbitConfig.DIRECT_ROUTER_KEY);
            data.setReturned(returnedMessage);
            template.convertAndSend(RabbitConfig.DIRECT_EXCHANGE_NAME,
                    RabbitConfig.DIRECT_ROUTER_KEY, dto, data);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}